package com.cnvp.paladin.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.eclipse.jetty.server.Authentication.User;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.interceptor.Global;
import com.cnvp.paladin.kit.StringKit;
import com.cnvp.paladin.kit.tree.TreeKit;
import com.cnvp.paladin.model.Phymapping;
import com.cnvp.paladin.model.Room;
import com.cnvp.paladin.model.SysDept;
import com.cnvp.paladin.model.SysRole;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.jfinal.aop.Before;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.kit.EncryptionKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

@ClearInterceptor(ClearLayer.ALL)
public class PassportController extends BaseController {

    @Before(Global.class)
    public void login() {
        String from = getPara("from");
        if (StringKit.notBlank(from))
            setAttr("from", from);
    }

    public void logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        redirect("/Passport/login");
    }

    public void dologin() {
        String is_app = getPara("is_app");
        Map<String, Object> json = new HashMap<String, Object>();
        Map data_1 = new HashMap();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(getPara("account"),
                EncryptionKit.md5Encrypt(getPara("password")));
        try {
            // 4、登录，即身份验证
            subject.login(token);
            String from = getPara("from");
            String findSql = "(1=1) and ";
            // 获取信息
            String account = token.getUsername();
            if (account != null)
                findSql += "account like '" + account + "' and ";
            findSql += " (1=1);";
            List<SysUser> data = SysUser.dao.where(findSql);
            int i = 0;
            SysUser data_need = data.get(i);
            String Account = data_need.getStr("account");
            String Email = data_need.getStr("email");
            String Avatar = data_need.getStr("url");
            int Id = data_need.getInt("id");
            data_1.put("id", Id);
            data_1.put("account", Account);
            data_1.put("email", Email);
            data_1.put("avatar", Avatar);
            json.put("code", "0");
            json.put("data", data_1);
            json.put("msg", "成功登陆");
            if ("1".equals(is_app)) {
                renderJson(json);
            } else {
                if (StringKit.isBlank(from))
                    redirect("/");
                else {
                    redirect(from);
                }
            }

        } catch (AuthenticationException e) {
            // 5、身份验证失败
            // alertAndGoback("用户名或密码错误，请重新登录");
            if ("1".equals(is_app)) {
                renderJson("{\"code\":\"330\",\"data\":\"\",\"msg\":\"failed\"}");
            } else {
                alertAndGoback("用户名或密码错误，请重新登录");
            }
        }
    }

    @Before(Global.class)
    public void password_forget() {
        String is_app = getPara("is_app");
        String account = getPara("account");
        String new1 = getPara("password");
        if (true) {
            // String findsql = "account =" + "\"" + account + "\";";
            // List<SysUser> user = SysUser.dao.where(findsql);
            // SysUser a = user.get(0);
            String sqlFind = "select * from cnvp_sys_user where account =" + "\"" + account + "\";";
            List<Record> user = Db.find(sqlFind);
            for (int i = 0; i < user.size(); i++)
                Db.update("cnvp_sys_user", user.get(i).set("password", EncryptionKit.md5Encrypt(getPara("password"))));
            // SysUser currentUser = (SysUser)
            // SecurityUtils.getSubject().getPrincipal();
            // currentUser = SysUser.dao.findById(currentUser.get("id"));
            // String new1 = getPara("new");
            // 先判断is_app是否为null
            if (is_app != null && is_app.equals("1")) {
                // SysUser.dao.set("id", a.get("id")).set("password",
                // EncryptionKit.md5Encrypt(new1)).update();
                // SysUser.dao.set("id", a.get("id")).set("password",
                // EncryptionKit.md5Encrypt(new1)).update();
                renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"密码修改成功\"}");
            } else {
                // SysUser.dao.set("id", a.get("id")).set("password",
                // EncryptionKit.md5Encrypt(new1)).update();
                alertAndGoback("密码修改成功");
            }
        }
    }

    /**
     * 点击注册之后的跳转方法 author：Lee time：2015/9/16
     */
    public void register() {
        render("../Register/register.html");
    }

    /**
     * 点击忘记密码后的跳转方法 author:Old time 2016/1/21
     */
    public void forget() {
        render("../Register/forget.html");
    }

    /**
     * 用户注册方法 author：Lee time：2015/9/16
     */
    public void create() {
        Map<String, Object> json = new HashMap<String, Object>();

        String is_app = getPara("is_app");

        if (isPost()) {

            SysUser model = getModel(SysUser.class, "user");
            String psw = model.getStr("password");
            // 加密
            model.set("password", EncryptionKit.md5Encrypt(psw));
            model.set("create_time", System.currentTimeMillis());
            model.set("create_user_id", 1);
            model.set("url", "504139779");
            // 账号
            String account = model.getStr("account");

            System.out.println(account);
            String findSql = "(1=1) and ";
            if (account != null)
                findSql += "account = '" + account + "' and ";
            findSql += " (1=1);";
            // 邮箱
            String email = model.getStr("email");
            String avatar = model.getStr("url");

            String findSql1 = "(1=1) and ";
            if (account != null)
                findSql1 += "email = '" + email + "' and ";
            findSql1 += " (1=1);";
            List<SysUser> data = SysUser.dao.where(findSql);
            List<SysUser> data1 = SysUser.dao.where(findSql1);
            // 正确情况
            if (data.size() != 0) {

                json.put("code", "308");
                json.put("data", "");
                json.put("msg", "用户名已注册");

                renderJson(json);
                return;

            } else if (data1.size() != 0) {

                json.put("code", "308");
                json.put("data", "");
                json.put("msg", "邮箱已注册");

                renderJson(json);
                return;

            } else {

                System.out.println(data);

                model.save();
                Integer id = model.getInt("id");

                // 在cnvp_sys_user_role中添加新注册的用户，权限置为1
                new SysUserRole().set("user_id", model.getInt("id")).set("role_id", 1).save();
                if (is_app != null && is_app.equals("1")) {
                    Map Data = new HashMap();
                    json.put("code", "0");
                    Data.put("id", id);
                    Data.put("account", account);
                    Data.put("email", email);
                    Data.put("avatar", avatar);
                    json.put("data", Data);
                    json.put("msg", "success");
                    renderJson(json);
                    // renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"success\"}");
                } else {
                    renderJson("注册成功！");
                }

            }

        }

    }

    public void noLogin_app() {
        renderJson("{\"code\":\"300\",\"data\":\"\",\"msg\":\"no login\"}");
    }

}
